# -*- coding: utf-8 -*-
from datetime import datetime
import maya.mel as mel
import maya.cmds as cmds
import subprocess
import re
import tempfile
import shutil
import os
#print(outputPath_Directory)
#outputTempPath = os.path.join(playblastTemp_folder,scenename + ".mov").replace("\\", "/")
class Check_Playblast():
	def Check_Playblast(self,outputPath_Directory):
		temp_folder = tempfile.gettempdir()

		scenepath = cmds.file(q=1,sn=1)
		scenepathsp = scenepath.split('/')
		scenename = scenepathsp[-1].split('.')[0]
		playblastTemp_folder =  os.path.join(temp_folder,scenename).replace("\\", "/")
		outputPath_Directory   = os.path.join(outputPath_Directory,scenename + ".mov").replace("\\", "/")
		width = 1920
		height = 1080
		fps = 25 
		Fontsize = 80
		Fontname = "Adobe Arabic"
		
		PrimaryColour= "&H00FFFAFA"#	"&H00FFF8F8"
		SecondaryColour= "&H00DC143C"  #   &HFFFF0000
		OutlineColour= "&H0000FFFF"
		BackColour= "&H00000000"
		BorderStyle = 1
		Outline = 0
		Shadow = 3 
		#assPath ="D:/wwwww/test_hud.ass"
		assPath = os.path.join(playblastTemp_folder, scenename + ".ass").replace("\\", "/")
		#exportpath = "D:/wwwww/eeeeee"
		exportpath = os.path.join(playblastTemp_folder, scenename).replace("\\", "/")
		#inP = "-i " + "D:/wwwww/eeeeee.%04d.png"
		inP = "-i " + exportpath + ".%04d.png"
		ffexe ="H:/RareWolf_Toolkit/Package/ffmpeg/ffmpeg.exe"
		
		
		list_headsUpDisplay = cmds.headsUpDisplay (listHeadsUpDisplays = 1)
		if list_headsUpDisplay:
			for i in list_headsUpDisplay:
				cmds.headsUpDisplay(i, remove=True)

		all_camera = [ i for i in cmds.listCameras(p=1) if i != 'persp' ]
		obj_list = []
		playblastCame=''
		for i in all_camera:
			if not cmds.referenceQuery(i, isNodeReferenced=True):
				obj_list.append(i)
				playblastCame = obj_list[0]
		for cam in cmds.ls ( type = 'camera' ):
			cmds.setAttr ( cam + '.rnd' , False )

		CameraShape = cmds.listRelatives(playblastCame,shapes=1)[0]
		cmds.setAttr(playblastCame + '.rnd', 1)
		'''
		#cmds.setAttr(playblastCame + ".displaySafeAction", 1)
		#cmds.colorManagementPrefs(e = 1,cmEnabled=1)
		cmds.displayPref(displayGradient=True)
		#cmds.setAttr ( 'hardwareRenderingGlobals.useMaximumHardwareLights' , 1 )
		cmds.setAttr ( 'hardwareRenderingGlobals.maxHardwareLights' , 4 )

		cmds.setAttr ( 'hardwareRenderingGlobals.enableTextureMaxRes' , 1 )
		cmds.setAttr ( 'hardwareRenderingGlobals.textureMaxResolution' , 512 )
		#cmds.setAttr ( 'hardwareRenderingGlobals.renderDepthOfField ' , 1)
		#cmds.setAttr ( 'hardwareRenderingGlobals.gammaCorrectionEnable ' , 1 )
		cmds.setAttr ( 'hardwareRenderingGlobals.gammaValue ' , 50)
		'''

		# 设置亮度调整值
		exposure_adjustment = 2
		'''
		# 设置渲染范围和文件输出路径
		start_frame = cmds.getAttr ( "defaultRenderGlobals.startFrame" )
		end_frame = cmds.getAttr ( "defaultRenderGlobals.endFrame" )
		output_path = "E:/test/Cam_abc/"

		# 渲染每一帧，保存并增加亮度
		for frame in range ( int ( start_frame ) , int ( end_frame ) + 1 ) :
			cmds.currentTime ( frame )
			# 进行批处理渲染
			cmds.render ( output_path + "frame_%04d.jpg" % frame , x = 1920 , y = 1080 )

			# 修改亮度
			cmds.displayRGBColor ( "perspShape" , 1.0 , 1.0 , 1.0 )  # 恢复显示颜色
			cmds.displayRGBColor ( "perspShape" , exposure_adjustment , exposure_adjustment , exposure_adjustment )  # 修改亮度
		'''

		#cmds.playblast ( filename = "E:/test/Mov/aaaaa.mov" , format = "qt" , sequenceTime = 0 , clearCache = 1 , viewer = 0 , showOrnaments = 1 , fp = 4 , fo = 1 , percent = 100 , compression = "H.264" , quality = 100 , widthHeight = [1080 , 720 ])

		cmds.playblast(format='image',filename = exportpath ,sequenceTime=0,clearCache=1,viewer=0,showOrnaments=1,fp=4,percent=100,compression="png",quality=100,widthHeight=(width,height))
		print("aaaaaaaaaaaaaaaaaaaaaaaaaa")
		hud_ass = ''
		hud_ass += "[Script Info]\n"	
		hud_ass += "ScriptType: v4.00\n"	
		hud_ass += "PlayResX: " + str(width)+"\n"	
		hud_ass += "PlayResY: " + str(height)+"\n"	
		hud_ass += "WrapStyle: 0\n"	
		hud_ass += "[V4+ Styles]\n"	
		hud_ass += "Format: Name, Fontname, Fontsize, PrimaryColour, SecondaryColour, OutlineColour, BackColour, Bold, Italic, Underline, StrikeOut, ScaleX, ScaleY, Spacing, Angle, BorderStyle, Outline, Shadow, Alignment, MarginL, MarginR, MarginV, Encoding\n"	 				
		hud_ass += "Style: ProjSize," + str(Fontname) + "," + str(Fontsize) +"," + str(PrimaryColour) + "," + str(SecondaryColour) + "," + str(OutlineColour) + "," + str(BackColour) + ",-1,0,0,0,60,60,0,0,"+  str(BorderStyle) +","+ str(Outline) +","+ str(Shadow) +",8,0,0,15,134\n"					  
		hud_ass += "Style: User," + str(Fontname) + "," + str(Fontsize) +"," + str(PrimaryColour) + "," + str(SecondaryColour) + "," + str(OutlineColour) + "," + str(BackColour) + ",-1,0,0,0,60,60,0,0,"+ str(BorderStyle) +","+ str(Outline) +","+ str(Shadow) +",1,10,0,50,134\n"	
		hud_ass += "Style: PCName," + str(Fontname) + "," + str(Fontsize) + "," + str(PrimaryColour) + "," +str( SecondaryColour) + "," + str(OutlineColour) + "," + str(BackColour) + ",-1,0,0,0,60,60,0,0,"+ str(BorderStyle) +","+ str(Outline) +","+ str(Shadow) +",1,10,0,10,134\n"	
		hud_ass += "Style: Date," + str(Fontname) + "," + str(Fontsize) + "," + str(PrimaryColour) + "," + str(SecondaryColour) + "," + str(OutlineColour) + "," + str(BackColour) + ",-1,0,0,0,60,60,0,0,"+ str(BorderStyle) +","+ str(Outline) +","+ str(Shadow) +",7,10,0,10,134\n"				   
		hud_ass += "Style: TimeCode," + str(Fontname) + "," + str(Fontsize) + "," + str(PrimaryColour) + "," + str(SecondaryColour) + "," + str(OutlineColour) + "," + str(BackColour) + ",-1,0,0,0,60,60,0,0,"+ str(BorderStyle) +","+ str(Outline) +","+ str(Shadow) +",3,0,0,50,134\n"	   				  
		hud_ass += "Style: Scene_text," + str(Fontname) + "," + str(Fontsize) + "," + str(PrimaryColour) + "," + str(SecondaryColour) + "," + str(OutlineColour) + "," + str(BackColour) + ",-1,0,0,0,60,60,0,0,"+ str(BorderStyle) +","+ str(Outline) +","+ str(Shadow) +",2,0,0,15,134\n"	  
		hud_ass += "Style: FocalLength_text," + str(Fontname) + "," + str(Fontsize) +"," + str(PrimaryColour) + "," + str(SecondaryColour) + "," + str(OutlineColour) + "," + str(BackColour) + ",-1,0,0,0,60,60,0,0,"+  str(BorderStyle) +","+ str(Outline) +","+ str(Shadow) +",9,0,10,50,134\n"	 
		hud_ass += "Style: FileCam_text," + str(Fontname) + "," + str(Fontsize) +"," + str(PrimaryColour) + "," + str(SecondaryColour) + "," + str(OutlineColour) + "," + str(BackColour) + ",-1,0,0,0,60,60,0,0,"+ str(BorderStyle) +","+ str(Outline) +","+ str(Shadow) +",9,0,10,10,134\n"			  
		hud_ass += "Style: Frame_text," + str(Fontname) + "," + str(Fontsize) + "," + str(PrimaryColour) + "," + str(SecondaryColour) + "," + str(OutlineColour) + "," + str(BackColour) + ",-1,0,0,0,60,60,0,0,"+ str(BorderStyle) +","+ str(Outline) +","+ str(Shadow) +",3,0,10,10,134\n"									   
		hud_ass += "\n"																																		  	
		hud_ass += "[Events]\n"
		increase_value= (100 / float(fps))
		MinTimes=int(cmds.playbackOptions( q=1, minTime=1))
		MaxTimes= int(cmds.playbackOptions( q =1,maxTime=1))
		File_sceneName = cmds.file(q=1, sceneName=1, shortName=1)
		
		PCName = os.environ.get ("COMPUTERNAME")
		hud_resolution = str (cmds.getAttr ("defaultResolution.width")) + " x " + str (cmds.getAttr ("defaultResolution.height"))
					
		frameRate = int(MaxTimes + 1 - MinTimes)
		
		
		now = datetime.now()
		time = now.strftime('%Y/%m/%d %H:%M:%S')
		for i in range(frameRate):
			#time = datetime.datetime.now ().strftime ('%Y/%m/%d %H:%M:%S')
			
			current_ms = str(((i+1)%fps)).zfill(2)
			current_sencond = str((i+1)/fps).split(".")[0]
			current_timeconde = current_sencond + ":" + current_ms
			CameFocalLength = cmds.getAttr (CameraShape + ".focalLength",time= MinTimes + i)
			hud_ass += self.wirte_ass_file(i,increase_value,playblastCame,hud_resolution,CameFocalLength,PCName,time,File_sceneName,current_timeconde,fps,MinTimes,MaxTimes)
		with open(assPath, 'w') as f:
			f.write(hud_ass.encode('utf-8'))
			f.close()
		
		audioOffset = 0
		audioFileCmd = ''
		AudioList= []
		
		Audios = cmds.ls(type = "audio")
		aPlayBackSliderPython = mel.eval('$tmpVar=$gPlayBackSlider')

		PlayBlastAudio = cmds.timeControl(aPlayBackSliderPython, q=1, s=1)
		if PlayBlastAudio:
			AudioList.append(PlayBlastAudio)
		if len(Audios)==1:
			if len(AudioList)==1:
				Audio = AudioList[0]
				audioOffset = int(cmds.getAttr(Audio + ".offset") - MinTimes)
				audioFile = cmds.sound(Audio, q=1, file=1)
			else:
				Audio  = Audios[0]
				audioOffset = int(cmds.getAttr(Audio + ".offset") - MinTimes)
				audioFile = cmds.sound(Audio, q=1, file=1)
		if not self.is_ascii(audioFile):
			print(u"存在中文")
			return(u"存在中文")
		offsetSec = float(audioOffset) / float(fps)
		#print (offsetSec)
		offsetCmd = ''
		if audioOffset > 0:
			offsetCmd += "-itsoffset " + str(offsetSec) + " "
		else:
			offsetCmd += "-ss " + str(abs(offsetSec)) + " "
		#print (offsetCmd)
		if len(audioFile) or os.path.exists(audioFile):#mel.eval('filetest - e audioFile')
			audioFileCmd = offsetCmd + "-i " + audioFile
		if not os.path.isfile(audioFile):
			audioFileCmd = ''
		timeRange = "-t " + str((MaxTimes - MinTimes + 1)/float(fps))
		s = " "
		start = "-start_number" + " " + str(MinTimes)
		
		#inP = "-i " + "D:/cam_0100.mov"
		#assP = "-vf subtitles=" "\\\'" + assPath + "\\\'"
		#assPath.replace()
		converted_path =assPath.replace("/","\\\\")
		converted_path = converted_path.replace(":", "\\:")
		assPaths =assPath.split("/")
		assP = ("-vf subtitles=" "\\\'" + converted_path + "\\\'")
		#assP = "-vf subtitles=" "\\'D\\:\\test_hud.ass\\'"
		outP = "-c:v libx264 -b 18000k -pix_fmt yuv420p -crf 1 -y " + outputPath_Directory
		hudInfo = [start,inP,audioFileCmd,timeRange,assP,outP]
		#hudInfo = [start,inP,assP,outP]
		command_line = ffexe + " " + s.join(hudInfo)
		#subprocess.Popen(command_line)
		os.popen(command_line)
		#shutil.copy(outputTempPath, outputPath_Directory)
		#for i in os.listdir(playblastTemp_folder):
		#	os.remove(playblastTemp_folder +"/"+ i)
			
		#shutil.rmtree(playblastTemp_folder)	
		return ("YES")
	def is_ascii(self,string):
		for char in string:
			if ord(char) > 127:
				return False
		return True

	def wirte_ass_file(self,i,increase_value,playblastCame,hud_resolution,CameFocalLength,PCName,time,File_sceneName,current_timeconde,fps,MinTimes,MaxTimes):
		hud_ass = ''
		hud_ass += "Dialogue: 0,0:00:00." + str(i * increase_value).zfill(2) +",0:00:00." + str(i * increase_value + increase_value).zfill(2) +",FileCam_text,,0,0,0,,"  + str(playblastCame) + "\n"
		hud_ass += "Dialogue: 0,0:00:00." + str(i * increase_value).zfill(2) +",0:00:00." + str(i * increase_value + increase_value).zfill(2) +",ProjSize,,0,0,0,," + hud_resolution + "\n"
		hud_ass += "Dialogue: 0,0:00:00." + str(i * increase_value).zfill(2) +",0:00:00." + str(i * increase_value + increase_value).zfill(2) +",FocalLength_text,,0,0,0,,"  + str(CameFocalLength) + "\n"
		hud_ass += "Dialogue: 0,0:00:00." + str(i * increase_value).zfill(2) +",0:00:00." + str(i * increase_value + increase_value).zfill(2) +",User,,0,0,0,," + "Frame " + str(i+1) + "\n"
		hud_ass += "Dialogue: 0,0:00:00." + str(i * increase_value).zfill(2) +",0:00:00." + str(i * increase_value + increase_value).zfill(2) +",PCName,,0,0,0,," + str(PCName) + "\n"
		hud_ass += "Dialogue: 0,0:00:00." + str(i * increase_value).zfill(2) +",0:00:00." + str(i * increase_value + increase_value).zfill(2) +",Date,,0,0,0,," + str(time) + "\n"
		hud_ass += "Dialogue: 0,0:00:00." + str(i * increase_value).zfill(2) +",0:00:00." + str(i * increase_value + increase_value).zfill(2) +",Scene_text,,0,0,0,,"  + str(File_sceneName) + "\n"
		hud_ass += "Dialogue: 0,0:00:00." + str(i * increase_value).zfill(2) +",0:00:00." + str(i * increase_value + increase_value).zfill(2) +",TimeCode,,0,0,0,," + current_timeconde + "(" + str(fps) + "fps)\n"
		hud_ass += "Dialogue: 0,0:00:00." + str(i * increase_value).zfill(2) +",0:00:00." + str(i * increase_value + increase_value).zfill(2) +",Frame_text,,0,0,0,," + str(MinTimes)  + "/" + str(i+1) + "/" + str(MaxTimes)  + "\n"
		return (hud_ass)